import React, { useState, useEffect } from 'react'
import moment from 'moment/moment';
import {AuthComponent,authModes} from '../../components/AuthComponent';
import api from '../../apis/user'
import { Table, Button, Popconfirm, message } from 'antd';

export default function AccountList() {
  const [list, setList] = useState([])
  const [loading, setLoading] = useState(false)
  const [total, setTotal] = useState(0)
  const [pageObj, setPage] = useState({ pageNumber: 1, pageSize: 5 })
  useEffect(() => {
    fetchData(pageObj)
  }, [])
  function fetchData(data) {
    setLoading(true)
    api.getAccountsList(data).then(res => {
      setList(res.data || [])
      setTotal(res.totalCount)
      setLoading(false)
    }).catch(err => {
      console.log(err);
      setLoading(false)
    })
  }
  function onChange(page, pageSize) {
    setPage({ pageNumber: page, pageSize })
    fetchData({ pageNumber: page, pageSize })
  }
  async function confirm(id) {
    await api.delAccountById(id)
    fetchData(pageObj)
  }
  const columns = [
    {
      title: '账户名',
      dataIndex: 'account',
    },
    {
      title: '角色',
      dataIndex: 'userGroup',
    },
    {
      title: '创建时间',
      dataIndex: 'updateDate',
      render: (text) => moment(text).format("YY-MM-DD HH-mm-ss")
    },
    {
      title: '操作',
      render: (_, item) =>
        <Popconfirm
          title="提示"
          description="您是否确认删除该数据?"
          onConfirm={() => confirm(item._id)}
        >
          <AuthComponent auth="del_account" authMode={authModes.openOrDisabled}>
            <Button type="primary" size="small">删除</Button>
          </AuthComponent>
        </Popconfirm>
    }
  ];


  return (
    <div className='addAccount'>
      <Table
        className="table"
        loading={loading}
        columns={columns}
        dataSource={list}
        rowKey="_id"
        pagination={{ defaultCurrent: 1, total, onChange, pageSizeOptions: [3, 5, 10], pageSize: pageObj.pageSize }}
        scroll={{ y: 460, scrollToFirstRowOnChange: true }}
      />
    </div>
  )
}
